<template>
  <el-card class="page-container">
    <template #header>
      <div class="header">
        <span>我的退房管理</span>
      </div>
    </template>
    
    <el-table :data="paidOrders" stripe :height="600" style="width: 100%">
      <el-table-column prop="id" label="订单ID"/>
      <el-table-column prop="hotelName" label="酒店名称"/>
      <el-table-column prop="roomType" label="房型"/>
      <el-table-column prop="amount" label="金额"/>
      <el-table-column prop="paymentMethod" label="支付方式"/>
      <el-table-column label="创建时间">
        <template #default="{ row }">
          {{ formatDate(row.createTime) }}
        </template>
      </el-table-column>
      <el-table-column label="支付时间">
        <template #default="{ row }">
          {{ formatDate(row.payTime) }}
        </template>
      </el-table-column>
      <el-table-column label="退房时间">
        <template #default="{ row }">
          <el-tooltip effect="dark" placement="top" v-if="row.checkoutTime || row.checkout_time">
            <template #content>{{ formatDate(row.checkoutTime || row.checkout_time) }}</template>
            <span>{{ formatDate(row.checkoutTime || row.checkout_time) }}</span>
          </el-tooltip>
          <span v-else>-</span>
        </template>
      </el-table-column>
      <el-table-column label="订单状态">
        <template #default="{ row }">
          <el-tag type="info" v-if="row.cancelTime">已取消</el-tag>
          <el-tag type="warning" v-else-if="!row.payTime">未支付</el-tag>
          <el-tag type="success" v-else-if="row.checkoutTime || row.checkout_time">已退房</el-tag>
          <el-tag type="primary" v-else>已支付</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="320px">
        <template #default="{ row }">
          <!-- 已支付但未退房的订单可以退房 -->
          <el-button 
            v-if="row.payTime && !(row.checkoutTime || row.checkout_time) && !row.cancelTime" 
            type="primary" 
            size="small" 
            @click="handleCheckout(row)"
          >
            退房
          </el-button>
          
          <!-- 已支付的订单可以续订 -->
          <el-button 
            v-if="row.payTime && !row.cancelTime" 
            type="success" 
            size="small" 
            @click="handleRebook(row)"
          >
            续订
          </el-button>
          
          <!-- 已支付的订单可以评论 -->
          <el-button 
            v-if="row.payTime && !row.cancelTime" 
            type="warning" 
            size="small" 
            @click="handleReview(row)"
          >
            评论
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <div class="pagination-box">
      <el-pagination background layout="total, sizes, prev, pager, next"
                     v-model:current-page="pageIndex"
                     v-model:page-size="pageSize"
                     :page-sizes="[10, 20, 50, 100]"
                     @size-change="handleSizeChange"
                     @current-change="handleCurrentChange"
                     :total="total"/>
    </div>
    
    <!-- 引入创建评论组件 -->
    <create-review ref="createReviewRef" @refresh="initData"/>
  </el-card>
</template>

<script setup lang="ts">
import { ref, onMounted, computed } from 'vue'
import { getUserOrders, checkoutOrder } from '@/api/order'
import { useUserInfoStore } from '@/stores/userInfo'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import CreateReview from '@/views/review/components/CreateReview.vue'

const router = useRouter()
const userInfoStore = useUserInfoStore()
const allOrders = ref([])
const total = ref(0)
const pageIndex = ref(1)
const pageSize = ref(20)
const createReviewRef = ref()

// 过滤出已支付的订单
const paidOrders = computed(() => {
  return allOrders.value.filter((order: any) => 
    order.payTime && !order.cancelTime
  );
})

// 格式化日期
const formatDate = (dateStr: string | null) => {
  if (!dateStr) return '-';
  const date = new Date(dateStr);
  return date.toLocaleString();
};

const initData = () => {
  // 确保用户已登录且有用户ID
  if (!userInfoStore.userInfo || !userInfoStore.userInfo.user || !userInfoStore.userInfo.user.userId) {
    ElMessage.warning('请先登录');
    return;
  }
  
  const userId = userInfoStore.userInfo.user.userId;
  console.log('开始获取用户订单列表数据...用户ID:', userId);
  
  getUserOrders(userId).then(res => {
    console.log('获取用户订单列表响应:', res);
    
    // 正确处理后端响应
    const result = res.data;
    console.log('后端返回的原始数据结构:', result);
    
    if (result && result.code === 200) {
      // 直接使用后端返回的数据
      allOrders.value = Array.isArray(result.data) ? result.data : [];
      
      // 处理字段名称差异
      allOrders.value = allOrders.value.map(item => {
        // 确保数据一致性，处理可能的checkoutTime/checkout_time命名差异
        if (item && item.checkout_time && !item.checkoutTime) {
          item.checkoutTime = item.checkout_time;
        }
        return item;
      });
      
      total.value = paidOrders.value.length;
      
      console.log('处理后的用户已支付订单数据:', paidOrders.value);
      
    } else {
      console.error('获取用户订单列表失败:', result);
      ElMessage.error(result?.msg || '获取订单列表失败');
    }
  }).catch(error => {
    console.error('获取用户订单列表错误:', error);
    ElMessage.error('网络错误，获取订单列表失败');
  });
}

const handleSizeChange = (size: number) => {
  pageSize.value = size;
  // 因为是前端分页，不需要重新加载数据
}

const handleCurrentChange = (index: number) => {
  pageIndex.value = index;
  // 因为是前端分页，不需要重新加载数据
}

// 处理退房
const handleCheckout = (row: any) => {
  if (!row.id) {
    ElMessage.error('订单ID不能为空');
    return;
  }
  
  ElMessageBox.confirm('确定要办理退房吗？', '提示', { type: 'warning' }).then(() => {
    console.log('准备办理退房:', row.id);
    
    checkoutOrder(String(row.id)).then(res => {
      console.log('退房响应:', res);
      
      const result = res.data;
      if (result && result.code === 200) {
        // 强制刷新数据
        setTimeout(() => {
          ElMessage.success('退房成功');
          initData(); // 刷新列表
        }, 500); // 延迟500ms刷新，确保后端数据已更新
      } else {
        ElMessage.error(result?.msg || '退房失败');
      }
    }).catch(error => {
      console.error('退房错误:', error);
      ElMessage.error('网络错误，退房失败');
    });
  }).catch(() => {
    // 用户取消操作
    console.log('用户取消退房操作');
  });
}

// 处理续订
const handleRebook = (row: any) => {
  if (!row.hotelName || !row.roomType) {
    ElMessage.error('无法获取酒店或房间信息');
    return;
  }
  
  // 将原订单信息存入sessionStorage，便于创建新订单页面使用
  sessionStorage.setItem('rebookInfo', JSON.stringify({
    hotelName: row.hotelName,
    roomType: row.roomType,
    originalOrderId: row.id
  }));
  
  // 跳转到创建订单页面
  router.push('/create-order');
}

// 处理评论
const handleReview = (row: any) => {
  if (!row.hotelName) {
    ElMessage.error('无法获取酒店信息');
    return;
  }
  
  // 将订单信息传递给评论组件
  createReviewRef.value.open(row);
}

onMounted(() => {
  initData();
})
</script>

<style scoped>
.header { display: flex; justify-content: space-between; align-items: center; }
.pagination-box { padding-top: 16px; display: flex; justify-content: right; }
</style> 